var express = require('express');
// 引入远程接口的调用方法
const shoppingAPI = require("../api/shopping");
// 创建了一个路由器
var router = express.Router();
const _ = require("lodash");


// 路由作用：和页面相关的操作
// 获取列表
router.get('/', async function (req, res, next) {
    // 获取浏览器发送的值type为GET，在query接收
    const { curPage, eachPage } = req.query;
    const data = await shoppingAPI.get({ curPage, eachPage });
    // 发送截取截取后的数据返回给页面
    res.send(data)
});

// 通过id查找
router.get('/findOne/:_id', async function (req, res, next) {
    // params去做路径解析
    const { _id } = req.params;
    const data = await shoppingAPI.findOne(_id);
    res.send(data)
});


// 通过购物车id查找
router.get('/findshop/:_id', async function (req, res, next) {
    // params去做路径解析
    const { _id } = req.params;
    const data = await shoppingAPI.findshop(_id);
    res.send(data)
});





// 更新图片数据
router.patch('/:_id', async function (req, res, next) {
    // 从url拿参数
    const { _id } = req.params;
    const data = req.body;
    // 传值更新
    await shoppingAPI.update({ _id }, data);
    // 返回更新的整条数据
    const result = await shoppingAPI.findOne({ _id });
    res.send(result)
});


// 删除照片路由
router.delete('/:_id/imgs/:url', async function (req, res, next) {
    // 从url拿参数
    const { _id, url } = req.params;
    await shoppingAPI.delImgs({ _id, url });
    //获取到修改保存后的最新数据并返回
    const data = await shoppingAPI.findOne({ _id });
    res.send(data);

});



router.post('/add', async function (req, res, next) {
    const { data } = req.body;
    const data2 = await shoppingAPI.addStudent( data );
    res.send(data2)
});


// 删除
router.post("/remove", async function (req, res, next) {
    const { _id } = req.body;
    await shoppingAPI.removeStudent({ _id });
    res.send({ status: true });
})

// 修改
router.put("/change", async function (req, res, next) {
    const {newData} = req.body;
    await shoppingAPI.changeStudent(newData);
    res.send({ status: true });
})
// 暴露接口
module.exports = router;
